<?php

namespace App\Http\Controllers\cz;

use App\Http\Controllers\Controller;
use App\Models\ChannelOrder;
use App\Models\CzChannel;
use App\Models\CzOrder;
use App\Models\CzOrderLog;
use App\Models\SysUser;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils;
use Darabonba\OpenApi\Models\Params;
use Darabonba\OpenApi\OpenApiClient;
use AlibabaCloud\OpenApiUtil\OpenApiUtilClient;
use Darabonba\OpenApi\Models\OpenApiRequest;



class CzOrderController extends Controller
{
    public function checkOrder(Request $request)
    {
        return 111;
        $h = date("H");
        // $h < 7 ||
        if ($h > 1 && $h < 7) {
            var_dump('Hour:' . $h);
            return success();
        }
        // if ($h > 01 && $h < 7) {
        //     var_dump('Hour:' . $h);
        //     return success();
        // }
        //定时查单
        $info = CzOrder::where('pay_status', 1)->orderBy('id', 'desc')->first();
        var_dump('最新订单时间' . $info->created_at);
        var_dump('当前时间' . date("Y-m-d H:i:s", time()));
        var_dump(time() - strtotime($info->created_at));
        if (time() - strtotime($info->created_at)  >= 20 * 60) {
            $res = $this->notifyMsg();
            if ($res == 'ok') {
                return success([], "检测并发送成功");
            } else {
                return error("检测成功,发送失败");
            }
        } else {
            return success([], '没有需要发送的订单');
        }
    }
    public function createApiInfo()
    {
        $params = new Params([
            // 接口名称
            "action" => "SendSms",
            // 接口版本
            "version" => "2017-05-25",
            // 接口协议
            "protocol" => "HTTPS",
            // 接口 HTTP 方法
            "method" => "POST",
            "authType" => "AK",
            "style" => "RPC",
            // 接口 PATH
            "pathname" => "/",
            // 接口请求体内容格式
            "reqBodyType" => "json",
            // 接口响应体内容格式
            "bodyType" => "json"
        ]);
        return $params;
    }
    // 通知消息
    public function notifyMsg()
    {

        $config = new Config([

            "accessKeyId" => "LTAI5t6q2tEBQegP5FauZpvX",
            // 必填，您的 AccessKey Secret
            "accessKeySecret" => "w9B2vyPb9ncoC1r1GwLyLCeCuz3AwH"
        ]);
        // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
        $config->endpoint = "dysmsapi.aliyuncs.com";
        $client = new Dysmsapi($config);
        $params = $this->createApiInfo();
        // $queries = [];
        // $queries["PhoneNumbers"] = "18379467634";
        // $queries["SignName"] = "熊志兴的博客";
        // $queries["TemplateCode"] = "SMS_463634304";
        $runtime = new RuntimeOptions([]);
        $request = new OpenApiRequest([
            "query" => OpenApiUtilClient::query([
                "PhoneNumbers" => "18379467634",
                "SignName" => "熊志兴的博客",
                "TemplateCode" => "SMS_463634304",
            ])
        ]);
        $request2 = new OpenApiRequest([
            "query" => OpenApiUtilClient::query([
                "PhoneNumbers" => "13510298888",
                "SignName" => "熊志兴的博客",
                "TemplateCode" => "SMS_463634304",
            ])
        ]);
        $request3 = new OpenApiRequest([
            "query" => OpenApiUtilClient::query([
                "PhoneNumbers" => "13823282548",
                "SignName" => "熊志兴的博客",
                "TemplateCode" => "SMS_463634304",
            ])
        ]);
        $res = $client->callApi($params, $request, $runtime);
        $res2 = $client->callApi($params, $request2, $runtime);
        $res3 = $client->callApi($params, $request3, $runtime);

        logger('发送结果' . json_encode($res));
        // logger('发送结果2' . json_encode($res2));
        // logger('发送结果3' . json_encode($res3));
        $res = json_decode(json_encode($res), 1);
        if ($res['statusCode'] == 200) {
            // return success([], "发送成功");
            return 'ok';
        } else {
            logger('发送失败' . json_encode($res));
            // return error("发送失败");
            return 'fail';
        }
        // try {
        //     // 复制代码运行请自行打印 API 的返回值
        //     $client->sendSmsWithOptions($sendSmsRequest, new RuntimeOptions([]));
        // } catch (Exception $error) {
        //     if (!($error instanceof TeaError)) {
        //         $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
        //     }
        //     // 如有需要，请打印 error
        //     logger('发送短信失败:' . $error->message);
        //     Utils::assertAsString($error->message);
        // }
    }
    public function addArea(Request $request)
    {
        $list =  CzOrder::where([
            "order_status" => 4,
            "create_by" => 92
        ])->where('msg', "like", "%获取归属地失败%")->get()->toArray();
        // dd($list);
        $arr = [];
        foreach ($list as $key => $val) {
            $mobile = $val['mobile'];
            $pre = substr($mobile, 0, 7);
            // dd($pre);
            $is_has = DB::table('phone')->where('phone', $pre)->first();
            if (!$is_has) {
                array_push($arr, $mobile);
            }
        }

        return success(['data' =>  array_unique($arr)]);
    }
    public function mxRefund(Request $request)
    {
        $user = SysUser::find(92);
        $num = 0;
        $orders = CzOrder::where('create_by', $user->id)->where('is_refund', 0)->where('order_status', 4)->get()->toArray();
        // dd($orders);
        foreach ($orders as $key => $val) {
            //检查是否有退款记录
            $refund_info = DB::table('cz_order_refund_log')->where('order_id', $val['id'])->first();
            if ($refund_info) {
                // logger('平台退款失败:订单已退过款1' . "订单号：" . $order['order_sn']);
                var_dump("订单已退过款2：" . $val['order_sn']);
                var_dump("\r\n");
                continue;
            }
            // dd($val['order_sn']);
            $balance_log = DB::table('balance_log')->where('type', 4)->where('order_sn', $val['order_sn'])->first();
            if ($balance_log) {
                // logger('平台退款失败:订单已退过款1' . "订单号：" . $order['order_sn']);
                var_dump("订单已退过款3：" . $val['order_sn']);
                var_dump("\r\n");
                continue;
            }
            // 进行退款
            DB::beginTransaction();
            try {
                $is_dec_balance = DB::table('sys_users')
                    ->where('id', $user->id)
                    ->increment('balance', $val['price']);
                if (!$is_dec_balance) {
                    DB::rollBack();
                }
                $res = DB::table('cz_order')->where('id', $val['id'])->update([
                    "is_refund" => 1,
                    "updated_at" => time(),
                ]);
                if (!$res) {
                    DB::rollBack();
                }
                $remark = "补退款|" . $val['mobile'] . "充值失败退款|" . $val['msg'];
                $balance_log_data = [
                    'order_sn' => $val['order_sn'],
                    'money' => $val['price'],
                    'bf_balance' => $user->balance,
                    'af_balance' => $user->balance + $val['price'],
                    'bank' => '',
                    'type' => 4,
                    'remark' => $remark,
                    'user_id' => $user->id,
                    'created_at' => strtotime($val['updated_at']),
                    'updated_at' => strtotime($val['updated_at']),
                ];
                $refund_log_data = [
                    'order_id' => $val['id'],
                    'created_at' => strtotime($val['updated_at']),
                    'price' => $val['price'],
                ];

                $b_res = DB::table('balance_log')->insert($balance_log_data);
                if (!$b_res) {
                    DB::rollBack();
                }
                $r_res = DB::table('cz_order_refund_log')->insert($refund_log_data);
                if (!$r_res) {
                    DB::rollBack();
                }

                DB::commit();
                $num++;
            } catch (QueryException $e) {
                DB::rollBack();
                var_dump($e->getMessage());
                var_dump('平台退款失败:QueryException' . "订单号：" . $val['order_sn']);
                var_dump("\r\n");
            }
        }
        dd($num);
        return success($orders);
    }
    public function updateOrderStatus(Request $request)
    {
        $params = $request->all();

        $mobile = trim($params['mobile']);
        $face_val = trim($params['val']);


        $order = DB::table('cz_order')->where('mobile', $mobile)->where('order_status', 2)
            ->where('is_auto', 0)
            ->where('face_value', $face_val)
            ->first();

        //以失败的订单跳过
        if (!$order) {
            return 'noexist';
            //            return error('订单不存在');
        }
        $msg = "批量回调完成";
        CzOrderLog::create([
            'order_id' => $order->id,
            'order_sn' => $order->order_sn,
            'content' => "批量回调完成",
        ]);

        //更新
        if ($msg) {
            $order->msg = substr($msg, 0, 100);
        }
        $row = DB::table('cz_order')->where('id', $order->id)->update([
            'order_status' => 3,
            'msg' => $msg,
            'updated_at' => time()
        ]);

        //异步回调
        sock_queue($order->id, 'callback_user_order');
        if ($row) {
            return 'ok';
        }
        return 'fail';
        return success([], '操作成功');
    }
    public function test()
    {
        $end_time = time() - 5 * 60;
        // 4*15*60*12
        // 查询一天内的订单
        $start_time = $end_time - 60 * 60 * 12;
        $arr = [];
        $channelOrder = ChannelOrder::where('channel_order_status', 2)->where('product_id', 33)->whereBetween('created_at', [$start_time, $end_time])->take(100)->get();
        // dd($channelOrder->toArray());
        foreach ($channelOrder->toArray() as $key => $val) {
            // dd(strtotime($val['created_at']));
            $order_id = $val['order_id'];
            $created_at = strtotime($val['created_at']);
            // 创建时间距离当前超过15分钟
            if (($end_time - $created_at) > 15 * 60) {
                array_push($arr, $val['order_sn']);
                sock_get(env('QUEUE_URL'), [
                    'act' => 'check_channel_order',
                    'order_id' => $order_id,
                    'push_order_sn' => $val['push_order_sn'],
                ]);
            }
        }
        return success(['data' => $arr]);

        $arr = [];
        $channelOrder = ChannelOrder::with(['order'])->whereIn('channel_order_status', [3, 4])->where('product_id', 7)->whereBetween('created_at', [1681315200, 1681660800])->get();
        // $channelOrder = ChannelOrder::with('order')->whereIn('channel_order_status', [3, 4])->where('product_id',7)->where('order_sn', "CZ20230410200074474733951")->get();
        // dd($channelOrder->toArray());
        foreach ($channelOrder->toArray() as $key => $val) {
            // dd($val['channel_order_status']);
            if ($val['order']['order_status'] !== $val['channel_order_status']) {
                // 
                $order_id = $val['order_id'];
                //确保渠道订单最新的状态
                $c_order = ChannelOrder::where('order_id', $order_id)->orderBy('created_at', 'desc')->first();
                // 
                if ($val['order']['order_status'] !== $c_order->channel_order_status) {
                    // dd($c_order->toArray());
                    // $order = DB::table('cz_order')->where('id', $order_id)->update([
                    //     "order_status"=>$val['channel_order_status'],
                    //     "updated_at"=>time()
                    // ]);
                    // sock_queue($order_id, 'callback_user_order');
                    array_push($arr, $val['order_sn']);
                }
                // return 111;
            }
        }
        return success(['data' => $arr]);

        // 在某个时间段中获取渠道订单完成，客户订单未完成的客户订单：注意：时间段需要修改和获取的条数，防止请求超时
        $list = DB::table('cz_channel_order')->whereIn('channel_order_status', [3, 4])->where('product_id', 7)->whereBetween('created_at', [1681056000, 1681747200])->take(1000)->get();
        $arr = [];
        foreach ($list->toArray() as $key => $val) {
            // dd($val);
            $order = DB::table('cz_order')->where('id', $val->order_id)->first();
            if ($order->order_status == 3 || $order->order_status == 4) {
                continue;
            } else {
                array_push($arr, $order->mobile);
            }
        }
        dd($arr);
        return success(['data' => $arr]);
    }
    public function asyncOrder(Request $request)
    {
        $channleOrder = ChannelOrder::with('order')->whereIn('channel_order_status', [3, 4])->where('product_id', 7)->whereBetween('created_at', [1681056000, 1681747200])->take(1000)->get();
        dd($channleOrder);
        $list = DB::table('cz_channel_order')->whereIn('channel_order_status', [3, 4])->where('product_id', 7)->whereBetween('created_at', [1681056000, 1681747200])->take(1000)->get();
        $arr = [];
        foreach ($list->toArray() as $key => $val) {
            // dd($val);
            $order = DB::table('cz_order')->where('id', $val->order_id)->first();
            if ($order->order_status == 3 || $order->order_status == 4) {
                continue;
            } else {
                array_push($arr, $order->mobile);
            }
        }
        // dd($arr);
        return success(['data' => $arr]);
        // return ;
    }
    public function testCb(Request $request)
    {
        // 获取请求模版
        // $channel_file = base_path('channel/template/') . "baseChannel.php";
        // include_once $channel_file;

        // $name = 'baseChannel';
        // $obj = new $name([]);
        // $url = "https://cz.wwbest.cn/official/order/test?id=1";
        // $res = $obj->httpRequest($url, "POST", ['a' => 1, 'b' => 3]);
        // return success(['data' => $res]);
        logger('请求参数' . json_encode($request->all()));
        return "success";
        return  request()->ip();
    }
    // 修改客户订单为缓存
    public function changeToCache(Request $request)
    {
        $params = $request->only(['order_ids', 'pwd']);
        $curTime = time();
        // pwd 相差10s不允许操作（）
        if ($curTime - $params['pwd'] > 10) {
            return error('无权限');
        }
        $res = DB::table('cz_order')->whereIn('id', $params['order_ids'])->update([
            "order_status" => 5,
            "updated_at" => time()
        ]);
        return success([
            "data" => $res
        ]);
    }
    // 清理渠道订单数据（失败）
    public function deleteChannelOrder(Request $request)
    {

        // $list = DB::table('cz_channel_order')->where('channel_order_status',4)->take(100)->get();
        // $first =  []
        // return success(['data'=>$list]);
        $curTime = time();
        $first = DB::table('cz_channel_order')->where('channel_order_status', 4)->orderBy('id', 'desc')->first();
        dd($first);
        $time = $curTime - $first->created_at;
        // 添加时间判断，最多只能删除到上个月
        if ($time > 31 * 24 * 60 * 60) {
            // return "超过一个月";
            // 删除记录
            $arr = [];
            $res = DB::table('cz_channel_order')->where('channel_order_status', 4)->take(20000)->delete();
            array_push($arr, $res);
            // for ($i=0; $i < 5; $i++) { 
            //     $res = DB::table('cz_channel_order')->where('channel_order_status', 4)->take(2000)->delete();
            //     array_push($arr,$res);
            // }
            $time2 = time() - $curTime;
            return success(['data' => [
                "count" => $arr,
                'exec_time' => $time2,
            ]]);
        } else {
            // 不允许删除
            return error('不做处理');
        }
        // return success(['data'=>($first)]);
    }
    public function refund(Request $request)
    {
        $params = $request->all();

        $mobile = trim($params['mobile']);
        $face_val = trim($params['val']);


        $order = DB::table('cz_order')->where('mobile', $mobile)->where('order_status', 2)
            ->where('is_auto', 0)
            ->where('face_value', $face_val)
            ->first();

        //以失败的订单跳过
        if (!$order) {
            return 'noexist';
        }
        $msg = "批量失败[" . date("YmdH") . "]";
        CzOrderLog::create([
            'order_id' => $order->id,
            'order_sn' => $order->order_sn,
            'content' => "批量失败",
        ]);

        //更新
        if ($msg) {
            $order->msg = substr($msg, 0, 100);
        }
        $row = DB::table('cz_order')->where('id', $order->id)->update([
            'order_status' => 4,
            'msg' => $msg,
            'updated_at' => time()
        ]);

        //异步退款
        sock_queue($order->id, 'order_refund');

        //异步回调
        sock_queue($order->id, 'callback_user_order');

        if ($row) {
            return 'ok';
        }
        return 'fail';
    }

    //通过批量订单号去改
    public function updateMobileStatus6ByBatchSn(Request $request)
    {
        $params = $request->all();

        $mobile = trim($params['mobile']);
        $batch_sn = trim($params['batch_sn']);

        $order = DB::table('cz_order')->where('mobile', $mobile)->where('order_status', 2)
            ->where('batch_order_sn', $batch_sn)
            ->where('is_auto', 0)
            ->first();

        //以失败的订单跳过
        if (!$order) {
            return 'noexist';
        }
        CzOrderLog::create([
            'order_id' => $order->id,
            'order_sn' => $order->order_sn,
            'content' => "批量手动拦截",
        ]);

        //更新
        $row = DB::table('cz_order')->where('id', $order->id)->update([
            'order_status' => 6,
            'updated_at' => time()
        ]);

        //异步回调
        sock_queue($order->id, 'callback_user_order');
        if ($row) {
            return 'ok';
        }
        return 'fail';
        return success([], '操作成功');
    }
    // 分发搞个接口，传参数产品id可多个，和多少秒，然后去查询上游的订单状态
    public function getChannelOrderStatus(Request $request)
    {
        logger(1111);
        $params = $request->only(['spec_ids', 'time']);
        $spec_ids = explode(',', $params['spec_ids']);
        $curTime = time();
        $endTime = $curTime - $params['time'];
        // $spec_ids = json_decode($params['spec_ids']);
        // DB::enableQueryLog();
        $list = DB::table('cz_channel_order')->where('channel_order_status', '2')->whereBetween('created_at', [strtotime(date('Y-m-d', time())), $endTime])->whereIn('spec_id', $spec_ids)->get();
        // return $list;
        //  1659008202
        // 获取模版 1654770278 1654770278
        // $list = $list->toArray();
        $success = [];
        $fail = [];
        $ing = [];
        $reqFail = [];
        foreach ($list as $key => $value) {
            sock_get(env('QUEUE_URL'), [
                'act' => 'check_channel_order',
                'order_id' => $value->order_id,
                'push_order_sn' => $value->push_order_sn,
            ]);
            // $channel = CzChannel::find($value->channel_id);
            // if (!$channel) {
            //     continue;
            // }
            // $channel_file = base_path('channel/template/') . "{$channel->channel_code}.php";
            // if (!file_exists($channel_file)) {
            //     // 渠道文件不存在
            //     continue;
            // }
            // $setting_arr = $channel->setting;
            // $setting = [];
            // foreach ($setting_arr as $v) {
            //     $setting[$v['name']] = $v['val'];
            // }
            // $setting['channel_code'] = $channel->channel_code;
            // $setting['channel_id'] = $value->channel_id;
            // $setting['callback_url'] = $channel->callback_url;
            // include_once $channel_file;
            // $obj = new $channel['channel_code']($setting);
            // if (method_exists($obj, 'queryOrder')) {
            //     $queryOrderParams = [
            //         'push_order_sn' => $value->push_order_sn,
            //         "channel_order_sn" => $value->channel_order_sn,
            //     ];
            //     $res = $obj->queryOrder($queryOrderParams);
            //     if ($res['code'] == 200) {
            //         if ($res['order_status'] == 3) {
            //             array_push($success, $value);
            //             //异步操作

            //         }
            //         if ($res['order_status'] == 4) {
            //             array_push($fail, $value);
            //         }
            //         if ($res['order_status'] == 2) {
            //             array_push($ing, $value);
            //         }
            //     } else {
            //         array_push($reqFail, $value);
            //     }
            // }
        }
        return success();
    }
    //查单 (渠道订单中已经成功，客户订单未成功) 2022-06-23
    public function asyncOrderStatus(Request $request)
    {
        // return error('不处理');
        // 2022-06-09 02:00:00
        // 2022-06-09 08:37:29
        // return 'success';
        // $res = DB::select('select * from `cz_channel_order` where `updated_at` between 1654711200 and 1654735049 and `channel_id` = 12 and `channel_order_status` = 3;');
        $orderSns = request('order_sn', []);
        if (!$orderSns) {
            return error('orderSns 不能为空');
        }
        if (!is_array($orderSns)) {
            return error('orderSns 格式错误');
        }
        $fail = [];
        $success = [];
        foreach ($orderSns as $key => $item) {
            $item = trim($item);
            $order = CzOrder::where('order_sn', $item)->first();
            // 查渠道订单状态
            // 获取最新的一条记录
            $channelOrder = ChannelOrder::where('order_sn', $item)->orderBy('id', 'DESC')->first();
            if (!$order && !$channelOrder) {
                // 不存在的订单 跳过
                array_push($fail, ['order_sn' => $item, 'msg' => '订单不存在或渠道订单不存在']);
                continue;
                // else if ($order->is_loop) {
                // 循环订单跳过
                // array_push($fail, ['order_sn' => $item, 'msg' => '无限重提订单不处理']);
                // continue;
                // } 
            } else {
                // 客户订单为充值中，渠道订单为成功或失败重新查单
                if ($order->order_status == 2 && ($channelOrder->channel_order_status == 3 || $channelOrder->channel_order_status == 4)) {
                    // 充值中进行查单
                    // dd($order);
                    if ($channelOrder->msg == '余额不足') {
                        // 余额不足进行压单
                        DB::table('cz_order')->where('order_sn', $item)->update([
                            "order_status" => 6,
                            "msg" => "[拦截]渠道余额不足",
                            "updated_at" => time(),
                        ]);
                        array_push($success, ['order_sn' => $item, 'msg' => '余额不足修改为压单']);
                    } else {
                        sock_get(env('QUEUE_URL'), [
                            'act' => 'async_customer_order_2',
                            'order_id' => $order->id,
                            'push_order_sn' => $channelOrder->push_order_sn,
                        ]);
                        array_push($success, ['order_sn' => $item, 'msg' => '当前订单已执行查单，稍后查看订单状态']);
                    }
                } else {
                    array_push($fail, ['order_sn' => $item, 'msg' => '当前订单状态正常不需要同步']);
                    continue;
                }
            }
        }
        logger('提交成功订单' . json_encode($success) . '成功数：' . count($success));
        logger('提交失败订单' . json_encode($fail) . '成功数：' . count($fail));
        return success(['data' => [
            'success_count' => count($success),
            'fail_count' => count($fail),
            'success_order_sn' => $success,
            'fail_order_sn' => $fail,
        ]]);
    }
    // 修改渠道订单中下单成功无响应的处理
    public function changeChannelOrderFail(Request $request)
    {
        // 获取当天下单成功的渠道订单且相应参数和请求参数为空的
        // 验证创建时间和当前时间相差五分钟以上的
        $end_time = time();
        $start_time = strtotime(date('Y-m-d'));
        $list = DB::table('cz_channel_order')
            ->where('post_data', null)->where('channel_data', null)
            ->where('channel_order_status', 1)
            ->where('product_id', 31)
            ->whereBetween('created_at', [time() - 60 * 20, time() - 3 * 60])
            ->get();
        // 
        // dd($list);

        $res = [];
        foreach ($list->toArray() as $key => $value) {
            // dd($value->id);
            // 修改为失败
            if (time() - $value->created_at > 5 * 60) {
                DB::table('cz_channel_order')->where('id', $value->id)->update([
                    "channel_order_status" => 4,
                    "msg" => "[手动]",
                    "updated_at" => time()
                ]);
                $row = DB::table('cz_order')->where('id', $value->order_id)->update([
                    'order_status' => 4,
                    'msg' => "[手动]",
                    'updated_at' => time()
                ]);
                array_push($res, $value->order_id);
                //异步退款
                sock_queue($value->order_id, 'order_refund');
                //异步回调
                sock_queue($value->order_id, 'callback_user_order');
            }
        }
        logger('下单成功需要修改的订单' . json_encode($res));
        return success(['order_ids' => $res], '操作成功');
    }

    public function getPhone(Request $request)
    {
        $phone = DB::table('phone')->orderBy('id', 'desc')->where('id', '>', "479500")->get();
        return success([
            "data" => $phone
        ]);
    }
    // 添加手机号
    public function setPhone(Request $request)
    {
        $url = "http://m.hfcz888.com:8080/api/getPhone";
        $res =  $this->httpRequest($url, "GET");
        $res_arr = json_decode($res, true);
        if ($res_arr['code'] == 200) {
            var_dump("获取到结果条数:" . count($res_arr['data']));
            echo "<br/>";
            $num = 0;
            foreach ($res_arr['data'] as $key => $val) {
                // dd($val);
                $isHas = DB::table('phone')->where('phone', $val['phone'])->first();
                // var_dump("添加条数:" . $isHas);
                // echo "<br/>";
                if (!$isHas) {
                    DB::table('phone')->insert([
                        "pref" => $val['pref'],
                        "phone" => $val['phone'],
                        "province" => $val['province'],
                        "city" => $val['city'],
                        "isp" => $val['isp'],
                        "post_code" => $val['post_code'],
                        "city_code" => $val['city_code'],
                        "area_code" => $val['area_code'],
                    ]);
                    $num++;
                }
            }
            var_dump("添加条数:" . $num);
            echo "<br/>";
            // DB::table('phone')->updateOrInsert();
        }
        // dd($res_arr['data']);
        // return success($res_arr);
    }
    public function getYcList(Request $request)
    {
        $mobile = request('mobile');
        $url = "http://m.hfcz888.com:8080/api/getYCOrderList?mobile=" . $mobile;
        $res = $this->httpRequest($url, 'GET');
        // var_dump($res);
        $res_arr = json_decode($res, true);
        return success(['data' => $res_arr['data']]);
    }
    public function httpRequest($url, $method, $postfields = null, $cookie = '', $refer = '', $headers = array(), $debug = false)
    {
        //header("Content-type:text/html;charset=utf-8");
        $method = strtoupper($method);
        $ci = curl_init();
        /* Curl settings */
        curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        //        curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0");
        curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36");
        curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 0); /* 在发起连接前等待的时间，如果设置为0，则无限等待 */
        curl_setopt($ci, CURLOPT_TIMEOUT, 120); /* 设置cURL允许执行的最长秒数 */
        curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
        switch ($method) {
            case "POST":
                curl_setopt($ci, CURLOPT_POST, true);
                if (!empty($postfields)) {
                    $tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
                    curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
                }
                break;
            default:
                curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); /* //设置请求方式 */
                break;
        }
        $ssl = preg_match('/^https:\/\//i', $url) ? TRUE : FALSE;
        curl_setopt($ci, CURLOPT_URL, $url);
        if ($ssl) {
            curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
            curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE); // 不从证书中检查SSL加密算法是否存在
        }
        //curl_setopt($ci, CURLOPT_HEADER, true); /*启用时会将头文件的信息作为数据流输出*/
        curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ci, CURLOPT_MAXREDIRS, 2);/*指定最多的HTTP重定向的数量，这个选项是和CURLOPT_FOLLOWLOCATION一起使用的*/
        curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ci, CURLINFO_HEADER_OUT, true);
        curl_setopt($ci, CURLOPT_COOKIE, $cookie);/* * *COOKIE带过去** */
        //伪造来源referer
        //        curl_setopt ($ci,CURLOPT_REFERER,'http://sb777.cn:8080/tohersystem/rechargeOrder.do?action=distribution&isDistribution=true');
        curl_setopt($ci, CURLOPT_REFERER, $refer);

        $response = curl_exec($ci);
        $requestinfo = curl_getinfo($ci);
        $http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
        if ($debug) {
            echo "=====post data======\r\n";
            var_dump($postfields);
            echo "=====info===== \r\n";
            print_r($requestinfo);
            echo "=====response=====\r\n";
            print_r($response);
        }
        curl_close($ci);
        return $response;
    }
}
